/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#pragma once

#include "gl_local.h"
#include "FreeImage.h"

/*-----------------------------------------------------------------------------
	GL render target manager :	
-----------------------------------------------------------------------------*/

//
//	EGLRTManager::EGLRTManager
//
EGLRTManager::EGLRTManager	( EGLDriver *driver ) : driver(driver)
{
	LOG_INIT("GL Render Target manager");
	
	driver->CheckGLExtension("GL_EXT_framebuffer_object");
	driver->CheckGLExtension("GL_EXT_framebuffer_blit");
	driver->CheckGLExtension("GL_EXT_packed_depth_stencil");
	
	stereo_target	=	GL_BACK;

	ResetFrameBuffer();	
}


//
//	EGLRTManager::~EGLRTManager
//
EGLRTManager::~EGLRTManager	( void )
{
	LOG_SHUTDOWN("GL Render Target manager");
}


/*-----------------------------------------------------------------------------
	Public stuff :	
-----------------------------------------------------------------------------*/

//
//	EGLRTManager::AllocRenderTarget
//
IPxTexture EGLRTManager::AllocRenderTarget( ERSFormat_t format, int width, int height )
{
	for (uint i=0; i<rt_pool.size(); i++) {
		
		if (rt_pool[i]->GetRefCount()!=1) {
			continue;
		}
		
		IPxTexture	rt	=	rt_pool[i];
		
		if (rt->GetWidth()==width && rt->GetHeight()==height && rt->GetFormat()==format) {
			return rt;
		}
	}

	IPxTexture	new_rt	=	new EGLRenderTarget2( format, width, height );
	
	rt_pool.push_back( new_rt );
	
	return new_rt;
}


//
//	EGLRTManager::ClearFrameBuffer
//
void EGLRTManager::ClearFrameBuffer( uint target, const EColor &color, float depth/*=1*/, uint stencil/*=0 */ )
{
	uint gl_target	=	0;
	if ( target & RS_CLEAR_COLOR	)	gl_target |= GL_COLOR_BUFFER_BIT;
	if ( target & RS_CLEAR_DEPTH	)	gl_target |= GL_DEPTH_BUFFER_BIT;
	if ( target & RS_CLEAR_STENCIL	)	gl_target |= GL_STENCIL_BUFFER_BIT;
	
	if (gl_target==0) {
		return;
	}
	
	glClearColor( color.x, color.y, color.z, color.w );
	glClearDepth( depth );
	glClearStencil( stencil );
	
	glClear( gl_target );
}


//
//	EGLRTManager::SetFrameBuffer
//
void EGLRTManager::SetFrameBuffer( IPxTexture ds, IPxTexture c0, IPxTexture c1/*=0*/, IPxTexture c2/*=0*/, IPxTexture c3/*=0 */ )
{
	if (!ds && !c0 && !c1 && !c2 && !c3) {
		ResetFrameBuffer();
		return;
	}
	
	current_frame_buffer.ds	=	ds;
	current_frame_buffer.c0	=	c0;
	current_frame_buffer.c1	=	c1;
	current_frame_buffer.c2	=	c2;
	current_frame_buffer.c3	=	c3;
	
	SetDrawFBOInternal( ds, c0, c1, c2, c3);
}


//
//	EGLRTManager::ResetFrameBuffer
//
void EGLRTManager::ResetFrameBuffer( void )
{
	GL_CALL( glBindFramebuffer( GL_DRAW_FRAMEBUFFER, 0 ) );
	GL_CALL( glBindFramebuffer( GL_READ_FRAMEBUFFER, 0 ) );
	
	current_frame_buffer.ds	=	NULL;
	current_frame_buffer.c0	=	NULL;
	current_frame_buffer.c1	=	NULL;
	current_frame_buffer.c2	=	NULL;
	current_frame_buffer.c3	=	NULL;
	
	uint w, h;
	driver->GetScreenSize(w, h);

	GL_CALL( glDrawBuffer( GL_BACK ) );
    GL_CALL( glViewport( 0, 0, w, h ) );
}


/*-----------------------------------------------------------------------------
	Data transfering :
-----------------------------------------------------------------------------*/

void EGLRTManager::CopyColorFrameData( IPxTexture dst, IPxTexture src, bool filter )
{
	SetReadFBOInternal( NULL, src );
	SetDrawFBOInternal( NULL, dst );	

	uint sw, sh, dw, dh;
	sw	=	src->GetWidth();
	sh	=	src->GetHeight();
	dw	=	dst->GetWidth();
	dh	=	dst->GetHeight();

	GL_CALL( glBlitFramebuffer( 0,0,sw,sh, 0,0,dw,dh, GL_COLOR_BUFFER_BIT, filter ? GL_LINEAR : GL_NEAREST) );

	SetFrameBuffer( current_frame_buffer.ds, 
					current_frame_buffer.c0, 
					current_frame_buffer.c1, 
					current_frame_buffer.c2, 
					current_frame_buffer.c3 );
}


void EGLRTManager::CopyDepthFrameData( IPxTexture dst, IPxTexture src )
{
	SetReadFBOInternal( src, NULL );
	SetDrawFBOInternal( dst, NULL );	
	
	uint w, h, sw, sh;
	driver->GetScreenSize( w, h );
	sw	=	src->GetWidth();
	sh	=	src->GetHeight();
	
	GL_CALL( glBlitFramebuffer( 0,0,sw,sh, 0,0,w,h, GL_DEPTH_BUFFER_BIT, GL_NEAREST) );

	SetFrameBuffer( current_frame_buffer.ds, 
					current_frame_buffer.c0, 
					current_frame_buffer.c1, 
					current_frame_buffer.c2, 
					current_frame_buffer.c3 );
}


//
//	EGLRTManager::CopyColorToBackBuffer
//
void EGLRTManager::CopyColorToBackBuffer( IPxTexture src, bool left, bool right, bool filter )
{
	GLenum	stereo_target	=	GL_BACK;
	
	if ( left && right	)	{	stereo_target	=	GL_BACK;		} else
	if ( left			)	{	stereo_target	=	GL_BACK_LEFT;	} else
	if ( right			)	{	stereo_target	=	GL_BACK_RIGHT;	} else 
							{	ASSERT(0);	}

	uint w, h, sw, sh;
	driver->GetScreenSize( w, h );
	sw	=	src->GetWidth();
	sh	=	src->GetHeight();
	
	SetReadFBOInternal( NULL, src );
	GL_CALL( glBindFramebuffer( GL_DRAW_FRAMEBUFFER, 0 ) );
	GL_CALL( glDrawBuffer( stereo_target ) );
	
	GL_CALL( glBlitFramebuffer( 0,0,sw,sh, 0,0,w,h, GL_COLOR_BUFFER_BIT, filter ? GL_LINEAR : GL_NEAREST ) );
	
	SetFrameBuffer( current_frame_buffer.ds, 
					current_frame_buffer.c0, 
					current_frame_buffer.c1, 
					current_frame_buffer.c2, 
					current_frame_buffer.c3 );
}


//
//	EGLRTManager::SetStereoTarget
//
void EGLRTManager::SetStereoTarget( bool left, bool right )
{
	stereo_target	=	GL_BACK;
	return;
	
	if ((left && right)) {
		stereo_target	=	GL_BACK;
	}
	if (left) {
		stereo_target	=	GL_BACK_LEFT;
	}
	if (right) {
		stereo_target	=	GL_BACK_RIGHT;
	}
}


/*-----------------------------------------------------------------------------
	Screenshot :
-----------------------------------------------------------------------------*/

//
//	EGLRTManager::MakeScreenshot
//
void EGLRTManager::MakeScreenshot( EString path, ERSImageFormat_t image_format )
{
	GLint				viewport_size[4];
	GLint				last_buffer;
	GLenum				gl_format	= GL_BGRA;
	uint				bpp			= 32;

	if(image_format == RS_JPG) {
		gl_format	= GL_BGR;
		bpp			= 24;
	}

	glGetIntegerv(GL_VIEWPORT, viewport_size);
	
	// Read bits from color buffer
	glPixelStorei(GL_PACK_ALIGNMENT,   1);
	glPixelStorei(GL_PACK_ROW_LENGTH,  0);
	glPixelStorei(GL_PACK_SKIP_ROWS,   0);
	glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

	IPxBlob b = CoreCreateBlob(viewport_size[2]*viewport_size[3]*(bpp/8));

	glGetIntegerv(GL_READ_BUFFER, &last_buffer);
	glReadBuffer(GL_FRONT);

	{
		//PROFILE_FUNCTION("glReadPixels");
		glReadPixels(0, 0, viewport_size[2], viewport_size[3], gl_format, GL_UNSIGNED_BYTE, b->GetBufferPointer());
	}

	// Set last used read buffer
	glReadBuffer(last_buffer);

	LOGF("Screenshot: %s%s", FileSystem()->getDirectory(), path.CStr());

	ifct()->SaveImageToFile(path, image_format, viewport_size[2], viewport_size[3], bpp, b->GetBufferPointer());
}


/*-----------------------------------------------------------------------------
	Internal stuff :
-----------------------------------------------------------------------------*/

//
//	EGLRTManager::AllocFBOInternal
//
GLuint EGLRTManager::AllocFBOInternal( GLuint ds, GLuint c0, GLuint c1, GLuint c2, GLuint c3 )
{
    GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };

	//	search fpr appropriate FBO config :
	for (uint i=0; i<fbo_pool.size(); i++) {
		FBO *fbo	=	&fbo_pool[i];
		
		if (fbo->depth_stencil	==	ds	&&	
			fbo->color0	== c0	&&	fbo->color1	== c1	&&	
			fbo->color2	== c2	&&	fbo->color3	== c3	
		) {
			return fbo->fbo_obj;
		}
	}
	
	LOGF("creating FBO : DS : %X | C : %X %X %X %X", ds, c0, c1, c2, c3);
	
	//
	//	Create new FBO config :
	//
	FBO new_fbo;
	
	glGenFramebuffers( 1, &new_fbo.fbo_obj );
	new_fbo.depth_stencil	=	ds;
	new_fbo.color0			=	c0;
	new_fbo.color1			=	c1;
	new_fbo.color2			=	c2;
	new_fbo.color3			=	c3;
	
	uint	nbuf = 0;
	if (c0)	nbuf = 1;
	if (c1)	nbuf = 2;
	if (c2)	nbuf = 3;
	if (c3)	nbuf = 4;
	
	GL_CALL( glBindFramebuffer( GL_FRAMEBUFFER, new_fbo.fbo_obj ) );
	
		if (nbuf) {
			GL_CALL( glDrawBuffers( nbuf, bufs ) );
		} else {
			GL_CALL( glDrawBuffer( GL_NONE ) );
			GL_CALL( glReadBuffer( GL_NONE ) );
		}

		GL_CALL( glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,			GL_TEXTURE_2D, c0, 0 ) );
		GL_CALL( glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,			GL_TEXTURE_2D, c1, 0 ) );
		GL_CALL( glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2,			GL_TEXTURE_2D, c2, 0 ) );
	    GL_CALL( glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3,			GL_TEXTURE_2D, c3, 0 ) );
	    GL_CALL( glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,	GL_TEXTURE_2D, ds, 0 ) );
	    
	    if ( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE) {
			uint err = glCheckFramebufferStatus( GL_FRAMEBUFFER );
			SIGNAL(va("Bad FBO configuration: code 0x%X", err));
		} 

	GL_CALL( glBindFramebuffer( GL_FRAMEBUFFER, 0 ) );
	
	fbo_pool.push_back( new_fbo );
	
	return new_fbo.fbo_obj;	
}


//
//	EGLRTManager::FreeFBOs
//
void EGLRTManager::FreeFBOs( void )
{
	for (uint i=0; i<fbo_pool.size(); i++) {
		GL_CALL( glDeleteFramebuffers( 1, &fbo_pool[i].fbo_obj ) );
	}
}


//
//	EGLRTManager::SetDrawFBOInternal
//
void EGLRTManager::SetDrawFBOInternal( IPxTexture ds, IPxTexture c0, IPxTexture c1/* =0 */, IPxTexture c2/* =0 */, IPxTexture c3/* =0 */ )
{
	uint width	=	0;
	uint height	=	0;
	uint nbuf	=	0;
	
	ASSERT( ds || c0 );
	
	if (ds) {
		width	=	ds->GetWidth();
		height	=	ds->GetHeight();
	}
	
	if (c0) {
		width	=	c0->GetWidth();
		height	=	c0->GetHeight();
	}
	
	GLuint	ds_obj	=	ds.as<EGLRenderTarget2>() ? ds.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c0_obj	=	c0.as<EGLRenderTarget2>() ? c0.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c1_obj	=	c1.as<EGLRenderTarget2>() ? c1.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c2_obj	=	c2.as<EGLRenderTarget2>() ? c2.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c3_obj	=	c3.as<EGLRenderTarget2>() ? c3.as<EGLRenderTarget2>()->GetTexObject() : 0;
	
	GLuint	fbo_obj	=	AllocFBOInternal( ds_obj, c0_obj, c1_obj, c2_obj, c3_obj );

	GL_CALL( glBindFramebuffer( GL_DRAW_FRAMEBUFFER, fbo_obj ) );
	
    GL_CALL( glViewport( 0, 0, width, height ) );
}


//
//	EGLRTManager::SetReadFBOInternal
//
void EGLRTManager::SetReadFBOInternal( IPxTexture ds, IPxTexture c0, IPxTexture c1/* =0 */, IPxTexture c2/* =0 */, IPxTexture c3/* =0 */ )
{
	GLuint	ds_obj	=	ds.as<EGLRenderTarget2>() ? ds.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c0_obj	=	c0.as<EGLRenderTarget2>() ? c0.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c1_obj	=	c1.as<EGLRenderTarget2>() ? c1.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c2_obj	=	c2.as<EGLRenderTarget2>() ? c2.as<EGLRenderTarget2>()->GetTexObject() : 0;
	GLuint	c3_obj	=	c3.as<EGLRenderTarget2>() ? c3.as<EGLRenderTarget2>()->GetTexObject() : 0;

	GLuint	fbo_obj	=	AllocFBOInternal( ds_obj, c0_obj, c1_obj, c2_obj, c3_obj );
	GL_CALL( glBindFramebuffer( GL_READ_FRAMEBUFFER, fbo_obj ) );
}


